package com.netease.yunxin.app.im.welcome

import android.app.ProgressDialog
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.EditText
import com.google.gson.Gson
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.impl.LoadingPopupView
import com.net.PolizeApi
import com.net.PostLogin
import com.net.PostReg
import com.net.RetrofitManager.of
import com.net.RxCompat.schedulersTransformer
import com.netease.nimlib.sdk.auth.LoginInfo
import com.netease.yunxin.app.im.R
import com.netease.yunxin.app.im.main.MainActivity
import com.netease.yunxin.app.im.utils.DataUtils
import com.netease.yunxin.app.im.utils.PreferencesUtils
import com.netease.yunxin.kit.alog.ALog
import com.netease.yunxin.kit.common.ui.activities.BaseActivity
import com.netease.yunxin.kit.corekit.im.IMKitClient
import com.netease.yunxin.kit.corekit.im.IMKitClient.account
import com.netease.yunxin.kit.corekit.im.login.LoginCallback
import com.salton123.crash.XCrashManager
import kt.toast
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import xcrash.XCrash

class LoginActivity : BaseActivity() {
    companion object {
        const val TAG = "LoginActivity"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        findViewById<View>(R.id.btnLogin).setOnClickListener { login() }
        findViewById<View>(R.id.btnRegister).setOnClickListener {
            val intent = Intent(this@LoginActivity, RegisterActivity::class.java)
            startActivity(intent)
        }
//        val etUsername = findViewById<EditText>(R.id.etUsername)
//        val etPassword = findViewById<EditText>(R.id.etPassword)
//        etUsername.setText("${account()}")
//        etPassword.setText("111111")
    }

    fun login() {
        val etUsername = findViewById<EditText>(R.id.etUsername)
        val etPassword = findViewById<EditText>(R.id.etPassword)
        val username = etUsername.text.toString().trim()
        val password = etPassword.text.toString().trim()
        if(username.isEmpty() or password.isEmpty()){
            toast("请填写完整账号密码")
            return
        }
        val postReg = PostLogin(username, password)
        val body =
            Gson().toJson(postReg).toRequestBody("application/json; charset=utf-8".toMediaType())
        progressDialog = XPopup.Builder(this@LoginActivity).dismissOnBackPressed(false)
            .isLightNavigationBar(true) //                            .asLoading(null, R.layout.custom_loading_popup)
            .asLoading()
            .setStyle(LoadingPopupView.Style.ProgressBar) as LoadingPopupView
        progressDialog?.show()
        of(PolizeApi::class.java).login(body).compose(schedulersTransformer()).subscribe({ ret ->
            when (ret.code) {
                200 -> {
                    loginToIM(username, ret.data)
                    progressDialog?.dismiss()
                }
                500 -> {
                    progressDialog?.dismiss()
                    toast("登陆失败,${ret.msg}")
//                    toRegister()
                }
                else -> {
                    progressDialog?.dismiss()
                    toast("登陆失败,${ret.msg}")
                }
            }
        }, {
            toast("登陆失败，错误信息：$it")
            progressDialog?.dismiss()
        })
    }

    var progressDialog: LoadingPopupView? = null
    private fun toRegister() {
        val etUsername = findViewById<EditText>(R.id.etUsername)
        val etPassword = findViewById<EditText>(R.id.etPassword)

        val username = etUsername.text.toString().trim()
        val password = etPassword.text.toString().trim()
        val postReg = PostReg(username, username, password)
        val body =
            Gson().toJson(postReg).toRequestBody("application/json; charset=utf-8".toMediaType())
        of(PolizeApi::class.java).regsiter(body).compose(schedulersTransformer()).subscribe({ ret ->
            if (ret.code == 200) {
                login()
                progressDialog?.dismiss()
            } else if (ret.code == 500) {
                toast("注册失败,${ret.msg}")
                progressDialog?.dismiss()
            } else {
                toast("注册失败,${ret.msg}")
                progressDialog?.dismiss()
            }
        }, {
            toast("注册失败，错误信息：$it")
            progressDialog?.dismiss()
        })
    }

    fun loginToIM(account: String, token: String) {
        val loginInfo = LoginInfo.LoginInfoBuilder.loginInfoDynamic(account, token)
            .withAppKey(DataUtils.readAppKey(this)).build()
        IMKitClient.loginIM(loginInfo, object : LoginCallback<LoginInfo> {
            override fun onError(errorCode: Int, errorMsg: String) {
                toast("登录失败,错误码:$errorCode,错误信息:$errorMsg")
                PreferencesUtils.putString("account", "")
                PreferencesUtils.putString("token", "")
            }

            override fun onSuccess(data: LoginInfo?) {
                showMainActivityAndFinish()
                PreferencesUtils.putString("account", data?.account)
                PreferencesUtils.putString("token", data?.token)
            }
        })
    }

    private fun showMainActivityAndFinish() {
        ALog.d(TAG, "showMainActivityAndFinish")
        val intent = Intent()
        intent.setClass(this, MainActivity::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
        this.startActivity(intent)
        finish()
    }

    override fun onDestroy() {
        super.onDestroy()
        progressDialog?.dismiss()
    }
}